<template>
  <!-- 订单费用信息 -->
  <div class="fee-pane">
    <!-- 统计 -->
    <div class="page-form-block">
      <summary-info :summaryList="summaryList" />
    </div>
    <a-divider />
    <!-- 费用相关信息 -->
    <page-form :model="feeForm" ref="feeFormRef" layout="vertical">
      <fee-pane
        :isReletOrder="true"
        :orderFeeIndex="0"
        :feeTypeSwitch="false"
        @viewPriceCalendar="viewPriceCalendarFn"
        @feeChange="feeChangeFn"
      />
    </page-form>
  </div>
  <!-- 价格日历 -->
  <!-- <price-calendar-modal ref="priceCalendarModalRef" /> -->
</template>

<script setup name="LongOrderForm">
  import { ref, inject, computed } from 'vue'
  import feePane from '../../components/order-fee/fee-pane.vue'
  import summaryInfo from '../../components/summary-info.vue'
  import {
    getStoreTemplateDetail,
    initFeeDetail,
    buildCostInfoParam,
    handleAddserviceDefaultFee,
  } from '../../components/order-fee/fee-utils.js'
  // import priceCalendarModal from '@/views/business/price/car-model/form/components/price-calendar-modal.vue'
  import { getPriceCalendar } from '@/api/business/price.js'
  import dayjs from 'dayjs'

  const form = inject('form')
  const feeForm = inject('feeForm')
  const dict = inject('dict')
  const feeFormRef = ref({})
  import { useSysDict } from '@/hooks/useDict'
  const sysDict = useSysDict(['short_order_acquisition_type'])

  const orderSourceName = computed(() => {
    let list = dict.orderSourceEnum
    let findResult = list?.find((item) => item.value == form.value.orderSource)
    return findResult ? findResult.label : '-'
  })
  const orderAcquisitionTypeName = computed(() => {
    let list = sysDict.short_order_acquisition_type
    let findResult = list?.find((item) => item.value == form.value.orderAcquisitionType)
    return findResult ? findResult.label : '-'
  })
  const summaryList = computed(() => {
    const formValue = form.value
    return [
      [
        {
          label: '预计租赁周期',
          value: `${dayjs(formValue.expectedUseCarTime).format('YYYY-MM-DD')} - ${dayjs(formValue.expectedReturnCarTime).format(
            'YYYY-MM-DD'
          )}`,
        },
        { label: '租期', value: formValue.rentDays },
        { label: '订单来源', value: orderSourceName.value },
      ],
      [
        { label: '订单获取方式', value: orderAcquisitionTypeName.value },
        { label: '车型', value: formValue.originalModelName },
      ],
    ]
  })
  // 费用变化
  const feeChangeFn = (item, val, index) => {
    let feeDetailList = feeForm.value.orderFee[0].feeDetailList
    let option = feeDetailList[index].childrenList
    let itemName = item.itemName
    if (itemName == '月租价（标准）') {
      let target = option.find((item) => item.itemName == '车辆租金')
      if (target) target.amount = val * calcRate.value
    }
    if (itemName == '手续费（标准）') {
      let target = option.find((item) => item.itemName == '手续费')
      if (target) target.amount = val * 1
    }
    if (itemName == '基础保险（标准）') {
      let target = option.find((item) => item.itemName == '基础保险')
      if (target) target.amount = val * calcRate.value
    }
  }
  // 读取门店模板配置，初始化 feeForm
  // form 聚焦部分字段是否发生变化
  const isChangeFormByProps = (propStrList, prevForm) => {
    let formVal = form.value
    return propStrList.some((prop) => formVal[prop] != prevForm[prop])
  }
  const storeTemplate = ref({})
  const initStoreTemplate = (prevForm, defaultFee) => {
    return new Promise((resolve) => {
      if (isChangeFormByProps(['siteId'], prevForm)) {
        getStoreTemplateDetail(form.value.siteId, 2, (template, templateId) => {
          storeTemplate.value = template
          let feeValue = feeForm.value
          initFeeDetail(feeValue, template)
          // 更新费用模板 id
          feeForm.value.orderFee[0].priceTemplateId = templateId
          // 初始化费用
          if (defaultFee) {
            handleDefaultFee(defaultFee, template)
          }
          resolve()
        })
      } else {
        // 初始化费用
        if (defaultFee) {
          handleDefaultFee(defaultFee, storeTemplate.value)
        }
        resolve()
      }
    })
  }

  // 获取默认费用
  // 车型价格模板 id
  const priceModelId = ref()
  const calcRate = ref()
  const handleDefaultFee = (defaultFee = {}, storeTemplate) => {
    // 由于下单车型改为非必填，此处 basePrice 可能为空
    const { basePrice, otherPrice, rate } = defaultFee
    // 未选择车型时，basicPrice为null
    if (basePrice) {
      priceModelId.value = basePrice.id
    } else {
      priceModelId.value = null
    }
    calcRate.value = rate
    let feeValue = feeForm.value
    let feeDetailList = feeValue.orderFee[0].feeDetailList
    // 处理增值服务费默认值，配置用户自定义费用时，按次|按日收费，此处rate为后端返回的单位天，用于计算按天计费费用
    handleAddserviceDefaultFee(feeDetailList, storeTemplate, rate)
    // 初始化其他费用
    feeDetailList.forEach((feeCategory) => {
      const { childrenList } = feeCategory
      // 默认系统计算的费用包含，基础费用，押金费用以及增值服务费中的例如上门取车费、夜间服务费等费用
      if (childrenList && childrenList.length > 0) {
        childrenList.forEach((feeItem) => {
          // 费用名称
          let feeName = feeItem.itemName
          // basicPrice 费用
          if (feeName == '月租价（标准）') {
            if (basePrice?.price >= 0) feeItem.amount = basePrice?.price
          }
          if (feeName == '手续费') {
            if (basePrice?.poundageAmount >= 0) feeItem.amount = basePrice?.poundageAmount
          }
          if (feeName == '手续费（标准）') {
            if (basePrice?.poundageAmount >= 0) feeItem.amount = basePrice?.poundageAmount
          }
          if (feeName == '基础保险（标准）') {
            if (basePrice?.insuranceAmount >= 0) feeItem.amount = basePrice?.insuranceAmount
          }
          if (feeName == '租车押金') {
            if (basePrice?.carDeposit >= 0) feeItem.amount = basePrice?.carDeposit
          }
          if (feeName == '违章押金') {
            if (basePrice?.illegalDeposit >= 0) feeItem.amount = basePrice?.illegalDeposit
          }
          // otherPrice 费用
          if (otherPrice && otherPrice.length > 0) {
            let findIndex = otherPrice.findIndex((item) => item.itemName == feeName)
            if (findIndex >= 0) {
              let fee = otherPrice[findIndex]
              feeItem.statics = true
              if (fee?.amount >= 0) {
                feeItem.amount = fee.amount
              }
            }
          }
        })
      }
    })
    // 当没有下单车型时，此时费用计算不会计算出下述几种费用，此时需要手动补充费用，补充0
    if (!basePrice) {
      feeDetailList.forEach((feeCategory) => {
        const { childrenList } = feeCategory
        if (childrenList && childrenList.length > 0) {
          childrenList.forEach((feeItem) => {
            // 费用名称
            let feeName = feeItem.itemName
            // basicPrice 费用
            if (
              ['月租价（标准）', '车辆租金', '手续费（标准）', '手续费', '基础保险', '基础保险（标准）', '租车押金', '违章押金'].includes(
                feeName
              )
            ) {
              feeItem.amount = 0
            }
          })
        }
      })
    }
  }
  // 查看价格日历
  const priceCalendarModalRef = ref()
  const viewPriceCalendarFn = () => {
    priceCalendarModalRef.value.open(form.value.originalModelName)
    // 获取价格日历信息
    const param = {
      priceModelId: priceModelId.value,
      calendarDateS: dayjs(form.value.expectedUseCarTime).startOf('month').format('YYYY-MM-DD HH:mm:ss'),
    }
    getPriceCalendar(param).then((res) => {
      const result = res.result
      priceCalendarModalRef.value.setPriceList(result)
    })
  }

  const getCostInfo = (callback) => {
    feeFormRef.value.validate((error) => {
      if (!error) {
        let costInfo = buildCostInfoParam(feeForm.value)
        callback(costInfo)
      }
    })
  }

  defineExpose({
    getCostInfo,
    initStoreTemplate,
  })
</script>

<style lang="less" scoped></style>
